// 前端代码 - Vue.js部分

<template>
  <div class="container mx-auto p-6">
    <h1 class="text-3xl font-bold mb-8 text-center">Word文档比对工具</h1>
    
    <!-- 文件上传区域 -->
    <div class="bg-gray-100 rounded-lg p-6 mb-8">
      <div class="grid grid-cols-1 md:grid-cols-2 gap-6">
        <div>
          <label class="block text-gray-700 font-medium mb-2">原始文档</label>
          <input type="file" @change="handleFile1Change" class="w-full p-2 border border-gray-300 rounded">
          <div v-if="fileName1" class="mt-2 text-sm text-gray-600">
            已选择: {{ fileName1 }}
          </div>
        </div>
        
        <div>
          <label class="block text-gray-700 font-medium mb-2">修订文档</label>
          <input type="file" @change="handleFile2Change" class="w-full p-2 border border-gray-300 rounded">
          <div v-if="fileName2" class="mt-2 text-sm text-gray-600">
            已选择: {{ fileName2 }}
          </div>
        </div>
      </div>
      
      <button @click="compareFiles" 
              class="mt-6 bg-blue-500 hover:bg-blue-700 text-white font-bold py-2 px-4 rounded"
              :disabled="!file1 || !file2">
        开始比对
      </button>
    </div>
    
    <!-- 比对结果区域 -->
    <div v-if="comparisonResult.success" class="mb-8">
      <h2 class="text-xl font-bold mb-4">比对结果</h2>
      
      <div class="grid grid-cols-1 md:grid-cols-2 gap-6">
        <div>
          <h3 class="font-bold mb-2">原始文档</h3>
          <div class="bg-white p-4 rounded border border-gray-200 max-h-[600px] overflow-auto">
            <div v-for="(line, index) in comparisonResult.originalLines" 
                 :key="index"
                 :class="getLineClass(index, 'original')"
                 class="p-1">
              {{ line }}
            </div>
          </div>
        </div>
        
        <div>
          <h3 class="font-bold mb-2">修订文档</h3>
          <div class="bg-white p-4 rounded border border-gray-200 max-h-[600px] overflow-auto">
            <div v-for="(line, index) in comparisonResult.revisedLines" 
                 :key="index"
                 :class="getLineClass(index, 'revised')"
                 class="p-1">
              {{ line }}
            </div>
          </div>
        </div>
      </div>
      
      <!-- 变更摘要 -->
      <div class="mt-8">
        <h3 class="font-bold mb-4">变更摘要 ({{ comparisonResult.changes.length }})</h3>
        <div v-for="(change, index) in comparisonResult.changes" 
             :key="index"
             class="mb-4 p-3 rounded border"
             :class="{
               'border-red-300 bg-red-50': change.type === 'DELETE',
               'border-green-300 bg-green-50': change.type === 'INSERT',
               'border-yellow-300 bg-yellow-50': change.type === 'CHANGE'
             }">
          <div class="font-medium">变更 {{ index + 1 }}: {{ getChangeTypeName(change.type) }}</div>
          
          <div class="mt-2" v-if="change.type !== 'INSERT'">
            <div class="text-red-700">原始内容 (行 {{ change.original.position + 1 }}):</div>
            <div class="ml-4 whitespace-pre-wrap">{{ change.original.lines.join('\n') }}</div>
          </div>
          
          <div class="mt-2" v-if="change.type !== 'DELETE'">
            <div class="text-green-700">修订内容 (行 {{ change.revised.position + 1 }}):</div>
            <div class="ml-4 whitespace-pre-wrap">{{ change.revised.lines.join('\n') }}</div>
          </div>
        </div>
      </div>
    </div>
    
    <!-- 错误信息 -->
    <div v-if="comparisonResult.error" class="bg-red-100 border border-red-400 text-red-700 px-4 py-3 rounded mb-4">
      <strong>错误:</strong> {{ comparisonResult.error }}
    </div>
    
    <!-- 加载中 -->
    <div v-if="loading" class="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50">
      <div class="bg-white p-6 rounded-lg">
        <div class="animate-spin rounded-full h-12 w-12 border-b-2 border-blue-500 mx-auto"></div>
        <p class="mt-4 text-center">正在比对文档，请稍候...</p>
      </div>
    </div>
  </div>
</template>

<script>
import { filecompare } from "@/api/demo/demo"

export default {
  name: "filecompareDemo",
  data() {
    return {
      file1: null,
      file2: null,
      fileName1: '',
      fileName2: '',
      comparisonResult: {
        success: false,
        changes: [],
        originalLines: [],
        revisedLines: [],
        error: null
      },
      loading: false
    }
  },
  methods: {
    handleFile1Change(event) {
      this.file1 = event.target.files[0];
      this.fileName1 = this.file1 ? this.file1.name : '';
    },
    
    handleFile2Change(event) {
      this.file2 = event.target.files[0];
      this.fileName2 = this.file2 ? this.file2.name : '';
    },
    
    async compareFiles() {
      if (!this.file1 || !this.file2) return;
      
      this.loading = true;
      this.comparisonResult = { success: false, changes: [], error: null };
      
      try {
        const formData = new FormData();
        formData.append('file1', this.file1);
        formData.append('file2', this.file2);
        
        // const response = await fetch('http://localhost:8446/demo/file/compare', {
        //   method: 'POST',
        //   body: formData
        // });
        
        // if (!response.ok) {
        //   throw new Error(`HTTP错误: ${response.status}`);
        // }
        
        // this.comparisonResult = await response.json();

        filecompare(formData).then(res => {
            this.comparisonResult = res.data;
                            /*上传成功处理*/
                                }).catch(err => {
                                    this.comparisonResult = { success: false, error: err.message };
                                    /*报错处理*/});
        
      } catch (error) {
        this.comparisonResult = { success: false, error: error.message };
      } finally {
        this.loading = false;
      }
    },
    
    getLineClass(lineIndex, documentType) {
      const lines = documentType === 'original' 
        ? this.comparisonResult.originalLines 
        : this.comparisonResult.revisedLines;
      
      if (!lines || lines.length === 0) return '';
      
      const change = this.comparisonResult.changes.find(change => {
        const chunk = documentType === 'original' ? change.original : change.revised;
        return lineIndex >= chunk.position && lineIndex < chunk.position + chunk.lines.length;
      });
      
      if (!change) return '';
      
      switch (change.type) {
        case 'DELETE':
          return documentType === 'original' ? 'bg-red-100' : '';
        case 'INSERT':
          return documentType === 'revised' ? 'bg-green-100' : '';
        case 'CHANGE':
          return documentType === 'original' ? 'bg-yellow-100' : 'bg-yellow-100';
        default:
          return '';
      }
    },
    
    getChangeTypeName(type) {
      switch (type) {
        case 'DELETE': return '删除';
        case 'INSERT': return '插入';
        case 'CHANGE': return '修改';
        default: return type;
      }
    }
  }
}
</script>

<style>
.container {
  max-width: 1200px;
}
</style>